import shelve
import os
import fileUtils
import tempfile


class ShelveDB:
    filename = "test"

    def __init__(self, filename):
        self.filename = self.getCachedDir() + "\\" + filename
        print(self.filename)

    def write(self, key, value):
        with shelve.open(self.filename) as shelf:
            shelf[key] = value

    def read(self, key, default):
        with shelve.open(self.filename) as shelf:
            res = shelf.get(key)
            if res is not None:
                return res
            else:
                return default

    def delete(self, key):
        with shelve.open(self.filename) as shelf:
            if key in shelf:
                del shelf[key]
            else:
                print(f"Key '{key}' not found.")

    def clear(self):
        with shelve.open(self.filename) as shelf:
            shelf.clear()

    def getCachedDir(self):
        # 获取系统临时目录
        cache_dir = tempfile.gettempdir() + r"\expressionAI"
        # cache_dir = os.environ['APPDATA'] + r"\expressionAI"
        fileUtils.create_dir_not_exist(cache_dir)
        return cache_dir


# 使用示例
if __name__ == "__main__":
    db = ShelveDB("expression.db")

    db.write("name", "Alice")
    db.write("age", 30)

    print("Name:", db.read("name"))
    print("Age:", db.read("age"))

    db.delete("age")

    print("After deleting age:")
    print("Name:", db.read("name"))
    print("Age:", db.read("age"))  # should return None
